package com.linkoog.devtools.http.request.http_response.response.response_body;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.ui.JBCardLayout;
import com.linkoog.devtools.http.request.common.ResponseBody;
import com.linkoog.devtools.http.request.common.ResponseBodyType;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.ErrorBodyPanel;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.NoneBodyPanel;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.text.HtmlBodyPanel;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.text.JSONBodyPanel;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.text.PlainTextBodyPanel;
import com.linkoog.devtools.http.request.http_response.response.response_body.body.text.XmlBodyPanel;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.LinkedHashMap;

public class ResponseBodyPanel extends JPanel implements Disposable {

    private final Project project;
    @NotNull
    private final JBCardLayout cardLayout;

    private ResponseBodyType currentBodyType;
    private LinkedHashMap<ResponseBodyType, BodyPanel> panels;

    public ResponseBodyPanel(Project project) {
        this.project = project;
        this.cardLayout = new JBCardLayout();
        setLayout(cardLayout);

        panels = buildPanels(project);
        panels.forEach((type, bodyPanel) -> add(bodyPanel.getPanel(), type.toString()));
        show(ResponseBodyType.ERROR);
    }

    public <T extends ResponseBody> void reset(@NotNull T responseBody){
        final BodyPanel bodyPanel = panels.get(responseBody.bodyType());
        if (bodyPanel != null){
            bodyPanel.resetResponseBody(responseBody);
            show(responseBody.bodyType());
        }
    }

    public void show(ResponseBodyType responseBodyType){
        currentBodyType = responseBodyType;
        cardLayout.show(this, responseBodyType.toString());
    }

    private LinkedHashMap<ResponseBodyType, BodyPanel> buildPanels(Project project){
        LinkedHashMap<ResponseBodyType, BodyPanel> panels = new LinkedHashMap<>();
        panels.put(ResponseBodyType.NONE, new NoneBodyPanel());
        panels.put(ResponseBodyType.ERROR, new ErrorBodyPanel(project));
        panels.put(ResponseBodyType.JSON, new JSONBodyPanel(project));
        panels.put(ResponseBodyType.XML, new XmlBodyPanel(project));
        panels.put(ResponseBodyType.HTML, new HtmlBodyPanel(project));
        panels.put(ResponseBodyType.PLAIN_TEXT, new PlainTextBodyPanel(project));

        return panels;
    }


    @Override
    public void dispose() {

    }
}
